package com.dinstar.dinlink.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import com.dinstar.dinlink.R;
import com.dinstar.dinlink.databinding.ActivityMainBinding;
import com.dinstar.dinlink.server.LockScreenMsgReceiver;
import com.dinstar.linphone.core.LinphoneManager;
import com.google.android.material.bottomnavigation.BottomNavigationView;


import java.util.List;
import java.util.Objects;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private static final String TAG = "--MainActivity--";
    private static final int RC_CAMERA_PERMISSION = 1;
//    private BroadcastEventReceiver mBroadcastEventReceiver = new BroadcastEventReceiver();

//    private String[] premissions = new String[]{
//            Manifest.permission.CAMERA,
//            Manifest.permission.RECORD_AUDIO,
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE
//    };

    private String mLoginAccount = "";

    private ActivityMainBinding binding;

    private LinphoneManager linphoneManager;
    private LockScreenMsgReceiver myBroadcastReceiver;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "MainActivity started");

        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_activity_main);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(binding.navView, navController);
        Intent i = this.getIntent();
        String host = i.getStringExtra("ip");
        String portValue = i.getStringExtra("port");
        String sipExtension = i.getStringExtra("account");
        String passwd = i.getStringExtra("passwd");
        String mode = i.getStringExtra("mode");
        int port = Objects.nonNull(portValue) && !"".equals(portValue) ? Integer.parseInt(portValue) : 0;
        Log.i(TAG, String.format("ip --> %s, port --> %d, sip account --> %s, sip passwd --> %s, mode --> %s", host, port, sipExtension, passwd, mode));
        // 检查相机权限
//        if (!hasCameraPermission()) {
//            EasyPermissions.requestPermissions(this, "Need Camera Permission", RC_CAMERA_PERMISSION, premissions);
//        }


        //使用linphone
        if ("linphone".equals(mode)) {
            LinphoneManager.getInstance()
                    .init(this)
                    .start();
            LinphoneManager.getInstance().Login(sipExtension,passwd,host,portValue);

//            linphoneManager = LinphoneManager.getInstance(this, new RegistrationCallback() {
//                @Override
//                public void none() {
//                    Log.i(TAG, "未登录");
//                }
//                @Override
//                public void progress() {
//                    Log.i(TAG, "登录 Progressing");
//                }
//                @Override
//                public void ok() {
//                    Log.i(TAG, "登录OK");
//                    toast("登录OK");
//                }
//                @Override
//                public void cleared() {
//
//                }
//
//                @Override
//                public void failed() {
//                    Log.i(TAG, "登录失败");
//                    toast("登录失败");
//                }
//            }, new PhoneStateCallback() {
//            });
//            linphoneManager.start();
//            linphoneManager.doRegister(sipExtension, passwd, host+ ":" + port, TransportType.Udp);
        } else {
            //使用pjssip
//            this.initSipStack(host, port, sipExtension, passwd);
        }


        initBroadcastReceiver();

    }

    private void initBroadcastReceiver(){
        // 创建IntentFilter实例
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.zx.lockscreenmsgdemo.LockScreenMsgReceiver");
        myBroadcastReceiver =new LockScreenMsgReceiver();
        // 动态注册系统广播

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(myBroadcastReceiver, intentFilter, Context.RECEIVER_EXPORTED);
        } else {
            registerReceiver(myBroadcastReceiver, intentFilter);
        }


//        registerReceiver(myBroadcastReceiver, intentFilter);
    }



//    private boolean hasCameraPermission() {
//        return EasyPermissions.hasPermissions(this, premissions);
//    }

//    private void initSipStack(String ip, int port, String account, String passwd) {
//        EventBus.getDefault().register(this);
//        mBroadcastEventReceiver.register(this);
//        SipServiceCommand.start(this);
//        SipAccountData user = new SipAccountData();
//        user.setRealm("dinstar.com");
//        user.setHost(ip);
//        user.setPort(port);
//        user.setUsername(account);
//        user.setPassword(passwd);
//        this.mLoginAccount = SipServiceCommand.setAccount(this, user);
//    }

    private void toast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
//        if (hasCameraPermission()) {
//        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

    }

//    @Subscribe(threadMode = ThreadMode.MAIN)
//    public void callComing(CallComingEvent event) {
//        PjsipAudioManager.getInstance().stopRingtone();
//        Context ctx = getApplicationContext();
//        Intent intent = new Intent(ctx, CallInActivity.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        intent.putExtra("caller", event);
//        ctx.startActivity(intent);
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(myBroadcastReceiver);


//        EventBus.getDefault().unregister(this);
//        SipServiceCommand.removeAccount(this, mLoginAccount);
//        SipServiceCommand.stop(this);
//        mBroadcastEventReceiver.unregister(this);
    }
}